package com.swt.gap.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.swt.gap.common.PageResult;
import com.swt.gap.common.RoleEnum;
import com.swt.gap.dao.*;
import com.swt.gap.model.entity.SysGroupUser;
import com.swt.gap.model.entity.SysRole;
import com.swt.gap.model.entity.SysUser;
import com.swt.gap.model.entity.SysUserRole;
import com.swt.gap.model.vo.UserAddVO;
import com.swt.gap.model.vo.UserEditVO;
import com.swt.gap.model.vo.UserInfoVO;
import com.swt.gap.model.vo.UserVO;
import com.swt.gap.service.SysUserService;
import com.swt.gap.util.UserLoginUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author tyh
 * @date 2020/4/15 22:11
 */

@Service
public class SysUserServiceImpl implements SysUserService {
    private final static String INIT_PASSWORD = "123456";
    private final SysUserMapper sysUserMapper;
    private final SysUserRoleMapper sysUserRoleMapper;
    private final SysGroupDao sysGroupDao;
    private final SysGroupUserDao sysGroupUserDao;
    private final SysRoleMapper sysRoleMapper;

    public SysUserServiceImpl(SysUserMapper sysUserMapper,
                              SysUserRoleMapper sysUserRoleMapper,
                              SysGroupDao sysGroupDao,
                              SysGroupUserDao sysGroupUserDao,
                              SysRoleMapper sysRoleMapper) {
        this.sysUserMapper = sysUserMapper;
        this.sysUserRoleMapper = sysUserRoleMapper;
        this.sysGroupDao = sysGroupDao;
        this.sysGroupUserDao = sysGroupUserDao;
        this.sysRoleMapper = sysRoleMapper;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addNewUser(UserAddVO userAddVO) {
        Integer userId = UserLoginUtils.getUserId();
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userAddVO, user);
        user.setCreatedTime(new Date());
        user.setIsDeleted(false);
        user.setPassword(UserLoginUtils.passwordEncoder(INIT_PASSWORD));
        user.setCreatedBy(userId);
        user.setActivated(true);
        int result = sysUserMapper.insertSelective(user);

        Optional.ofNullable(userAddVO.getRoleId()).ifPresent(roleId ->{
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(user.getUserId());
            sysUserRoleMapper.insert(userRole);
        });

        Optional.ofNullable(userAddVO.getGroupId()).ifPresent(groupId ->{
            SysGroupUser userRole = new SysGroupUser();
            userRole.setGroupId(groupId);
            userRole.setUserId(user.getUserId());
            sysGroupUserDao.insert(userRole);
        });
        return result;
    }

    @Override
    public Boolean judgeName(String userName, Integer userId) {
        SysUser record = sysUserMapper.selectOneByName(userName);
        if(record == null){
            return false;
        }
        if(userId != null){
            return !record.getUserId().equals(userId);
        }
        return true;
    }

    @Override
    public Integer updateName(String userName, Integer userId) {
        boolean judge = this.judgeName(userName, userId);
        if(judge){
            SysUser sysUser = new SysUser();
            sysUser.setUserName(userName);
            sysUser.setUserId(userId);
            return sysUserMapper.updateByPrimaryKeySelective(sysUser);
        }
        return -1;
    }

    @Override
    public Integer deleteUser(Integer userId) {
        return sysUserMapper.deleteUser(userId);
    }

    @Override
    public UserInfoVO getUserInfo(Integer userId) {
        UserInfoVO user = sysUserMapper.selectUserInfo(userId);
        switch (RoleEnum.getByCode(user.getRoleId())) {
            case SUPER:
            case ADMIN:
                user.setHasAdminPermission(true);
                break;
            default:
                user.setHasAdminPermission(false);
                break;
        }
        return user;
    }

    @Override
    public PageResult<UserInfoVO> getUserListByPage(Integer pageNum, Integer pageSize, String key, Integer roleId) {
        //判断页数
        if(pageNum < 1){
            pageNum = 1;
        }
        //分页
        PageHelper.startPage(pageNum,pageSize);
        Page<UserInfoVO> users = sysUserMapper.selectUserListByKey(key, roleId);
        return new PageResult<>(users);
    }

    @Override
    public PageResult<UserInfoVO> listUser(Integer pageNum, Integer pageSize, String keyword, Integer departmentId) {
        Integer currentUserId = UserLoginUtils.getUserId();
        if(null == pageNum || pageNum < 1){
            pageNum = 1;
        }
        if(null == pageSize || pageSize < 1){
            pageSize = 10;
        }
        //分页
        PageHelper.startPage(pageNum,pageSize);
        List<Integer> roleIds = new ArrayList<>();


        List<SysRole> userRoles = listUserAccessRole(currentUserId);
        userRoles.forEach(userRole -> roleIds.add(userRole.getRoleId()));

        Page<UserInfoVO> users = sysUserMapper.listUser(keyword, roleIds, departmentId);
        users.getResult().forEach(user -> user.setGroups(sysGroupDao.selectByUserId(user.getUserId())));
        return new PageResult<>(users);

    }

    @Override
    public Integer resetPassword(Integer userId) {
        String newPassword = UserLoginUtils.passwordEncoder(INIT_PASSWORD);
        return sysUserMapper.updatePwd(userId, newPassword);

    }

    @Override
    public Integer updateUserPassword(Integer userId, String newPassword) {
        SysUser user = sysUserMapper.selectByPrimaryKey(userId);
        user.setPassword(UserLoginUtils.passwordEncoder(newPassword));
        return sysUserMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public Boolean judgePassword(Integer userId, String password) {
        SysUser record = sysUserMapper.selectByPrimaryKey(userId);
        String checkedPassword = UserLoginUtils.passwordEncoder(password);
        return checkedPassword.equals(record.getPassword());
    }

    @Override
    public SysUser getUserByName(String userName) {
        return sysUserMapper.selectOneByName(userName);
    }

    @Override
    public Integer getUserIdByName(String userName) {

        return sysUserMapper.selectIdByName(userName);
    }

    @Override
    public List<UserVO> getUsers() {
        return sysUserMapper.selectIdsAndNames();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateUser(UserEditVO userEditVO) {

        if(null != userEditVO.getRoleId()) {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userEditVO.getUserId());
            userRole.setRoleId(userEditVO.getRoleId());
            sysUserRoleMapper.updateUserRole(userRole);
        }

        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userEditVO, sysUser);
        return sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    @Override
    public PageResult<UserInfoVO> listUserByDepartmentId(Integer pageNum, Integer pageSize, String keyword, Integer departmentId) {
        //判断页数
        if(null == pageNum || pageNum < 1){
            pageNum = 1;
        }
        if (null == pageSize || pageSize < 1) {
            pageSize = 10;
        }
        //分页
        PageHelper.startPage(pageNum,pageSize);
        Page<UserInfoVO> users = sysUserMapper.selectByDepartmentId(keyword, departmentId);
        users.getResult().forEach(u -> u.setGroups(sysGroupDao.selectByUserId(u.getUserId())));
        return new PageResult<>(users);
    }

    @Override
    public PageResult<UserInfoVO> listUserByGroupId(Integer pageNum, Integer pageSize, String keyword, Integer groupId) {
        //判断页数
        if(null == pageNum || pageNum < 1){
            pageNum = 1;
        }
        if (null == pageSize || pageSize < 1) {
            pageSize = 10;
        }
        //分页
        PageHelper.startPage(pageNum,pageSize);
        Page<UserInfoVO> users = sysUserMapper.selectByGroupId(keyword, groupId);
        return new PageResult<>(users);
    }

    @Override
    public List<SysRole> listUserAccessRole(Integer userId) {
        List<SysRole> returnVal = new ArrayList<>();
        List<SysRole> userRoles = sysUserRoleMapper.listUserAccessRole(userId);
        if (!CollectionUtils.isEmpty(userRoles)) {
            switch (RoleEnum.getByCode(userRoles.get(0).getRoleId())) {
                case SUPER:
                    returnVal.add(new SysRole(RoleEnum.ADMIN.getCode(), RoleEnum.ADMIN.getName()));
                    returnVal.add(new SysRole(RoleEnum.USER.getCode(), RoleEnum.USER.getName()));
                    break;
                case ADMIN:
                    returnVal.add(new SysRole(RoleEnum.USER.getCode(), RoleEnum.USER.getName()));
                    break;
                default:
                    break;
            }
        }
        return returnVal;
    }

    @Override
    public Boolean hasAdminPerms() {
        Integer loginId = UserLoginUtils.getUserId();
        SysRole sysRole = sysRoleMapper.selectRoleByUserId(loginId);

        return sysRole != null &&
                (RoleEnum.SUPER.getCode().equals(sysRole.getRoleId()) || RoleEnum.ADMIN.getCode().equals(sysRole.getRoleId()));
    }
}
